# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)


from WebBase import Base

class Upload(Base):

    @view_config(route_name='AppWebUploadIndexRoute', renderer='../../templates/AppWebUploadIndex.pt')
    def AppWebUploadIndexRoute(self):
        tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        #why check again if user is in the session?
        #below looks like dead code
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait}
        return map

    @view_config(route_name='AppWebUploadRoute', request_method='POST')
    def AppWebUploadRoute(self):
        postParams =  self.request.POST
        #print postParams.getone('image_file')
        #print postParams.getone('image_file').type
        #print postParams.getone('image_file').filename
        #print dir(postParams.getone('image_file').filename)

        #print postParams
        category, name, material, size, weight, aperture, price, description, url ='', '', '', '', '', '', '', '', ''
        try:
            category = postParams.getone('category')
            name = postParams.getone('name')
            material = postParams.getone('material')
            size = postParams.getone('size')
            weight = postParams.getone('weight')
            aperture = postParams.getone('aperture')
            price = postParams.getone('price')
            description = postParams.getone('description')
            url = postParams.getone('url')

            log.debug('[category]' + category)
            log.debug('[name]' + name)
            log.debug('[material]' + material)
            log.debug('[size]' + size)
            log.debug('[weight]' + weight)
            log.debug('[aperture]' + aperture)
            log.debug('[price]' + price)
            log.debug('[description]' + description)
            log.debug('[url]' + url)
        except Exception, e:
            log.error(e)

        #file name passed by js
        #uploadName = postParams.getone('image_file').filename
        uploadFileList = postParams.getall('image_file')
        if uploadFileList:
            for uploadFile in uploadFileList:
                uploadName = uploadFile.filename

                #file type, jpg/bmp/gif/png/tiff.etc
                fileType = uploadFile.type
                #this suffix
                suffix = ""
                if fileType == "image/jpeg":
                    suffix = 'jpg'
                elif fileType == "image/bmp":
                    suffix = 'bmp'
                elif fileType == "image/gif":
                    suffix = 'gif'
                elif fileType == "image/png":
                    suffix = 'png'
                elif fileType == "image/tiff":
                    suffix = 'tiff'
                else:
                    suffix = 'ERRORTYPE'

                # The file instance
                input_file = uploadFile.file
                fileMD5 = HashUtil.getFileMD5(input_file.read())
                fileName = fileMD5 + '.' + suffix

                # The file path
                file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
                temp_file_path = file_path + '.tmp'
                input_file.seek(0)
                folderName = file_path[0: file_path.rfind('/') + 1]
                if not os.path.exists(folderName):
                    os.makedirs(folderName)

                with open(temp_file_path, 'wb') as output_file:
                    shutil.copyfileobj(input_file, output_file)
                os.rename(temp_file_path, file_path)

                thumb_path = os.path.join('/media/thumb', fileMD5[0: 2], fileMD5[2: 4], fileName)
                thumb_path = thumb_path.replace(suffix, 'jpg')
                ImageUtil.make_thumb(file_path, thumb_path, 200, 100)

                #self.request.session['email'] = email
                UploadTasks.uploadImgByQueue(fileMD5, file_path, self.request.session['tel'], category, \
                    name, material, size, weight, aperture, price, description, url)
            return Response("上传成功！")
        else:
            log.error('No....File')
            return Response("上传失败！")

    #上传背景图接口
    @view_config(route_name='AppWebUpLoadBgImgRoute', request_method='POST')
    def AppWebUpLoadBgImgRoute(self):
        postParams =  self.request.POST
        name = postParams.get('name', '')
        description = postParams.get('description', '')
        price = postParams.get('price', '0')
        log.debug('[name]' + name)
        log.debug('[description]' + description)
        try:
            tel = self.request.session['tel']
            uploadFileList = postParams.getall('image_file')

        except Exception, e:
            log.error(e)
            return Response("上传失败！")

        if uploadFileList:
            for uploadFile in uploadFileList:
                uploadName = uploadFile.filename

                #file type, jpg/bmp/gif/png/tiff.etc
                fileType = uploadFile.type
                log.debug('[fileType]' + fileType)
                #this suffix
                suffix = ""
                if fileType == "image/jpeg":
                    suffix = 'jpg'
                elif fileType == "image/bmp":
                    suffix = 'bmp'
                elif fileType == "image/gif":
                    suffix = 'gif'
                elif fileType == "image/png":
                    suffix = 'png'
                elif fileType == "image/tiff":
                    suffix = 'tiff'
                else:
                    suffix = 'ERRORTYPE'

                # The file instance
                input_file = uploadFile.file
                fileMD5 = HashUtil.getFileMD5(input_file.read())
                fileName = fileMD5 + '.' + suffix

                # The file path
                file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
                temp_file_path = file_path + '.tmp'
                input_file.seek(0)
                folderName = file_path[0: file_path.rfind('/') + 1]
                if not os.path.exists(folderName):
                    os.makedirs(folderName)

                with open(temp_file_path, 'wb') as output_file:
                    shutil.copyfileobj(input_file, output_file)
                os.rename(temp_file_path, file_path)

                thumb_path = os.path.join('/media/thumb', fileMD5[0: 2], fileMD5[2: 4], fileName)
                thumb_path = thumb_path.replace(suffix, 'jpg')
                ImageUtil.make_thumb(file_path, thumb_path, 200, 100)

                selectSQL = "SELECT * FROM user_info WHERE tel = %s"
                resultSelect = MySqlCRUD.selectImpl(selectSQL, tel)
                log.debug(resultSelect[0])
                timeStamp = datetime.now()
                image_source_type = resultSelect[0]['type']
                ######查询图片本身是否存在
                #查询语句，查询该图片md5是否存在记录；
                imgExitsSQL = '''
                    SELECT bgimage.MD5 FROM bgimage
                        WHERE bgimage.MD5 = %s;
                '''
                imgExistsResult = MySqlCRUD.selectImpl(imgExitsSQL, fileMD5)
                if imgExistsResult:
                    pass
                else:
                    imgInsertSQL = '''
                        INSERT INTO bgimage (MD5, path, name, description, timestamp, image_source_type, price)
                            VALUES(%s, %s, %s, %s, %s, %s, %s)
                    '''
                    resultImgInsert = MySqlCRUD.insertImpl(imgInsertSQL, fileMD5, file_path, name, description, timeStamp, image_source_type, price)
                    log.debug('[timeStamp]' + str(timeStamp))
                    log.debug('[DONE] AFFECTED_ROW[' + str(resultImgInsert) +']')

                insertSQL = '''
                    INSERT INTO user_bgimage_info (MD5, user_id, timestamp)
                        VALUES(%s, %s, %s) ON DUPLICATE KEY UPDATE timestamp = %s
                '''
                resultImgInsert = MySqlCRUD.insertImpl(insertSQL, fileMD5, resultSelect[0]['ID'], datetime.now(), datetime.now())
                log.debug('[SETUSERIMAGE][DONE] AFFECTED_ROW[' + str(resultImgInsert) +']')

            return Response("上传成功！")
        else:
            log.error('No....File')
            return Response("上传失败！")

    #上传背景图页面
    @view_config(route_name='AppWebUpLoadBgImgIndexRoute', renderer='../../templates/AppWebBgImgUpload.pt')
    def AppWebUpLoadBgImgIndexRoute(self):
        tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        #why check again if user is in the session?
        #below looks like dead code
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait}
        return map
